const express = require("express");
const Router = express.Router();
const md5 = require("blueimp-md5");
const {
  isEntryParame,
  verifiPhone
} = require("../../utils/validate/validate");
const {
  createTime
} = require("../../utils/time/time");
// const { login } = require("../../view/user/index");
const configSql = require("../../db/db");
const setToken = require('../../utils/token/token')
const request = require("request");
const queryString = require("querystring");
// 角色分配
/**
 *  1: 管理员
 *  2: 已登录
 *  3: 游客(未登录)
 *
 * */

// login(登录)
Router.post("/login", (req, res, next) => {
  let {
    username,
    password
  } = req.body;
  let obj = {
    username,
    password,
  };
  isEntryParame(obj, (d) => {
    if (!d.boo) {
      res.status(500).send({
        code: 500,
        msg: d.msg,
      });
      return;
    }
  });
  configSql(`SELECT * FROM user WHERE username='${username}'`).then(
    (result) => {
      if (result.length) {
        password = md5(password);
        configSql(`SELECT * FROM user WHERE username='${username}'and password='${password}'`).then(
          (data) => {
            if (data.length) {
              let token = setToken(username, password);
              res.status(200).send({
                code: 0,
                msg: "登录成功",
                token,
                info: data[0],
                uid: data[0].uid
              });
            } else {
              res.status(200).send({
                code: 400,
                msg: "密码错误,请重新输入",
              });
            }
          }
        );
      } else {
        res.send({
          code: 400,
          msg: "没有此账号,立即去注册",
        });
      }
    }
  );
});

// register(注册)
Router.use("/register", (req, res, next) => {
  let {
    username,
    phone,
    password
  } = req.body;
  let obj = {
    username,
    phone,
    password,
  };
  // 参数缺失验证
  isEntryParame(obj, (d) => {
    if (!d.boo) {
      res.status(500).send({
        code: 500,
        msg: d.msg,
      });
      return;
    }
  });

  let sql = `select * from user where username='${username}'`;
  configSql(sql).then((result) => {
    if (result.length) {
      res.status(200).send({
        code: 400,
        msg: "此用户名已存在,请重新注册",
      });
    } else {
      no_encryption = password; // 没有加密的密码
      password = md5(password); //  加密后的密码

      let insetSql = `insert into user(username,no_encryption,phone,password,register_time,role)values('${username}','${no_encryption}','${phone}','${password}','${createTime()}','2')`;
      configSql(insetSql).then((data) => {
        // console.log(data);
        res.status(200).send({
          code: 0,
          msg: "注册成功",
        });
      });
    }
  });
});

// 获取短信验证接口
Router.post("/msg_send", (req, res) => {
  let {
    phone
  } = req.body;
  let obj = {
    phone,
  };
  // 验证手机号码
  verifiPhone(obj, (d) => {
    if (!d.boo) {
      res.status(500).send({
        code: 500,
        msg: d.msg,
      });
      return;
    }
  });

  let queryData = queryString.stringify({
    mobile: phone, // 接收短信的用户手机号码
    tpl_id: "", // 申请的短信模板ID
    tpl_value: "", // 模板变量,根据实际情况修改
    key: "", // 申请的key(应用详情页查询)
  });
  let queryUrl = "连接接口地址" + queryData;
  request(queryUrl, (error, response, body) => {
    if (!error && response.statusCode == 200) {
      console.log(body);
      let jsonObj = JSON.parse(body); // 解析接口返回的JSON内容
      console.log(jsonObj);
    } else {
      console.log("请求异常");
    }
  });
});

// 获取用户信息(根据id 查询单个用户信息)
Router.get("/getInfo", (req, res, next) => {
  let {
    uid
  } = req.query;
  if (!uid) {
    res.send({
      code: 500,
      msg: "参数缺失",
    });
    return;
  }
  let sql = `select uid,username,phone,avatar,role from user where uid='${uid}'`;
  configSql(sql).then((result) => {
    res.send({
      code: 0,
      msg: "获取成功",
      result: result[0],
    });
  });
});

// 获取用户信息(查询用户列表)(后台管理系统)
Router.use("/info_list", (req, res, next) => {
  // 角色验证
  let {
    role
  } = req.body;
  if (role !== 1) {
    res.status(404).send({
      code: "404",
      msg: "找不到此接口",
    });
  }
  let sql = `select id,user_name,phone,avatar,name from user_list`;
  configSql(sql).then((result) => {
    res.send({
      code: 0,
      msg: "获取成功",
      result,
    });
  });
});

// 修改密码
Router.use("/edit_password", (req, res) => {
  let {
    user_name,
    old_password,
    new_password
  } = req.body;
  let select_sql = `select * from user_list where no_encryption='${old_password}' and user_name='${user_name}'`;
  configSql(select_sql).then((result) => {
    if (!result.length) {
      res.status(400).send({
        code: 400,
        msg: "密码错误",
      });
    } else {
      no_encryption = new_password;
      password = md5(new_password);
      let update_sql = `update user_list set password = '${password}'where no_encryption='${no_encryption}' and user_name='${user_name}'`;
      configSql(update_sql).then((data) => {
        res.status(200).send({
          code: 0,
          msg: "修改成功",
        });
      });
    }
  });
});

// 忘记密码
Router.use("/forget_password", (req, res) => {

});

module.exports = Router;